package com.example.hosptial.newController;

import com.example.hosptial.model.enity.Admin;
import com.example.hosptial.model.enity.Bed;
import com.example.hosptial.model.enity.Department;
import com.example.hosptial.service.BedService;
import com.example.hosptial.service.DoctorManagementService;
import jakarta.servlet.http.HttpSession;
import lombok.RequiredArgsConstructor;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.http.ResponseEntity;
import org.springframework.stereotype.Controller;
import org.springframework.ui.Model;
import org.springframework.web.bind.annotation.*;
import org.springframework.web.servlet.mvc.support.RedirectAttributes;

import java.util.HashMap;
import java.util.List;
import java.util.Map;

/**
 * 病床管理Controller
 */
@Controller
@RequestMapping("/admin")
@RequiredArgsConstructor
public class BedManagementController {

    private static final Logger logger = LoggerFactory.getLogger(BedManagementController.class);
    private final BedService bedService;
    private final DoctorManagementService doctorManagementService;

    /**
     * 显示病房管理页面
     */
    @GetMapping("/ward-manage")
    public String showWardManagePage(HttpSession session, Model model) {
        Admin admin = (Admin) session.getAttribute("admin");
        if (admin == null) {
            return "redirect:/admin/auth/login";
        }
        return "admin/ward-manage";
    }

    /**
     * 获取所有科室列表（用于病房管理）
     */
    @GetMapping("/ward-departments")
    @ResponseBody
    public ResponseEntity<List<Department>> getWardDepartments() {
        try {
            List<Department> departments = doctorManagementService.getAllDepartments();
            return ResponseEntity.ok(departments);
        } catch (Exception e) {
            logger.error("获取科室列表失败: {}", e.getMessage());
            return ResponseEntity.badRequest().build();
        }
    }

    /**
     * 获取病房列表
     */
    @GetMapping("/wards")
    @ResponseBody
    public ResponseEntity<?> getWards(@RequestParam(required = false) Integer deptId) {
        try {
            List<Map<String, Object>> wards = bedService.getWardsByDepartment(deptId);
            return ResponseEntity.ok(wards);
        } catch (Exception e) {
            logger.error("获取病房列表失败: {}", e.getMessage());
            return ResponseEntity.badRequest().body(Map.of("error", e.getMessage()));
        }
    }

    /**
     * 获取病房详细信息
     */
    @GetMapping("/wardDetail")
    @ResponseBody
    public ResponseEntity<?> getWardDetail(@RequestParam Integer wardId) {
        try {
            List<Map<String, Object>> beds = bedService.getWardBedDetails(wardId);
            return ResponseEntity.ok(beds);
        } catch (Exception e) {
            logger.error("获取病房详情失败: {}", e.getMessage());
            return ResponseEntity.badRequest().body(Map.of("error", e.getMessage()));
        }
    }

    /**
     * 获取病房的护士信息
     */
    @GetMapping("/ward-nurses")
    @ResponseBody
    public ResponseEntity<?> getWardNurses(@RequestParam Integer wardId) {
        try {
            List<Map<String, Object>> nurses = bedService.getWardNurses(wardId);
            return ResponseEntity.ok(nurses);
        } catch (Exception e) {
            logger.error("获取病房护士信息失败: {}", e.getMessage());
            return ResponseEntity.badRequest().body(Map.of("error", e.getMessage()));
        }
    }

    /**
     * 添加新病床
     */
    @PostMapping("/addBed")
    @ResponseBody
    public ResponseEntity<?> addBed(@RequestParam Integer wardId, HttpSession session) {
        Admin admin = (Admin) session.getAttribute("admin");
        if (admin == null) {
            return ResponseEntity.status(401).body(Map.of("error", "未登录或会话已过期"));
        }

        try {
            logger.info("开始添加病床，病房ID: {}", wardId);
            Bed newBed = bedService.addBed(wardId);
            
            Map<String, Object> response = new HashMap<>();
            response.put("success", true);
            response.put("message", String.format("病床添加成功：%d号床", newBed.getBedNum()));
            response.put("bedId", newBed.getBedId());
            response.put("bedNum", newBed.getBedNum());
            
            logger.info("病床添加成功，床位ID: {}, 床号: {}", newBed.getBedId(), newBed.getBedNum());
            return ResponseEntity.ok(response);
        } catch (IllegalArgumentException e) {
            logger.warn("添加病床参数错误: {}", e.getMessage());
            return ResponseEntity.badRequest().body(Map.of(
                "success", false,
                "error", e.getMessage()
            ));
        } catch (Exception e) {
            logger.error("添加病床失败: {}", e.getMessage(), e);
            return ResponseEntity.badRequest().body(Map.of(
                "success", false,
                "error", "添加病床失败: " + e.getMessage()
            ));
        }
    }

    /**
     * 获取病房的所有床位（AJAX调用）
     */
    @GetMapping("/beds/{wardId}")
    @ResponseBody
    public ResponseEntity<?> getWardBeds(
            @PathVariable Integer wardId,
            HttpSession session) {
        Admin admin = (Admin) session.getAttribute("admin");
        if (admin == null) {
            return ResponseEntity.status(401).body(Map.of("error", "未登录或会话已过期"));
        }

        try {
            List<Map<String, Object>> beds = bedService.getWardBedDetails(wardId);
            return ResponseEntity.ok(beds);
        } catch (Exception e) {
            logger.error("获取床位信息失败: {}", e.getMessage());
            return ResponseEntity.badRequest().body(Map.of("error", "获取床位信息失败: " + e.getMessage()));
        }
    }

    /**
     * 获取所有空闲床位（AJAX调用）
     */
    @GetMapping("/beds/available")
    @ResponseBody
    public ResponseEntity<?> getAvailableBeds(HttpSession session) {
        Admin admin = (Admin) session.getAttribute("admin");
        if (admin == null) {
            return ResponseEntity.status(401).body(Map.of("error", "未登录或会话已过期"));
        }

        try {
            List<Bed> beds = bedService.getAvailableBeds();
            return ResponseEntity.ok(beds);
        } catch (Exception e) {
            logger.error("获取空闲床位失败: {}", e.getMessage());
            return ResponseEntity.badRequest().body(Map.of("error", "获取空闲床位失败: " + e.getMessage()));
        }
    }

    /**
     * 更新床位状态
     */
    @PostMapping("/beds/{bedId}/status")
    public String updateBedStatus(
            @PathVariable Integer bedId,
            @RequestParam Integer status,
            HttpSession session,
            RedirectAttributes redirectAttributes) {
        Admin admin = (Admin) session.getAttribute("admin");
        if (admin == null) {
            return "redirect:/admin/auth/login";
        }

        try {
            bedService.updateBedStatus(bedId, status);
            redirectAttributes.addFlashAttribute("success", "床位状态更新成功");
        } catch (IllegalArgumentException e) {
            redirectAttributes.addFlashAttribute("error", e.getMessage());
        } catch (Exception e) {
            logger.error("更新床位状态失败: {}", e.getMessage());
            redirectAttributes.addFlashAttribute("error", "更新床位状态失败: " + e.getMessage());
        }
        return "redirect:/admin/ward/beds";
    }
}